package com.example.villagedevelop.generator.controller;

import com.example.villagedevelop.generator.entity.Users;
import com.example.villagedevelop.generator.service.LoginLogService;
import com.example.villagedevelop.generator.service.UserService;
import com.example.villagedevelop.generator.util.TokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
@Slf4j
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    LoginLogService loginLogService;


    @PostMapping("/login")
    public String login(@RequestBody Users users, HttpServletRequest request, HttpSession session) throws JsonProcessingException {
        int state = userService.search(users.getUsername(), users.getPassword());
        String ip = loginLogService.getIp(request);
        loginLogService.record(users.getUsername(),ip,state);

        if(state == 2){
            String token = TokenUtil.sign(users);
            HashMap<String,Object> hs=new HashMap<>();
            hs.put("token",token);
            ObjectMapper objectMapper=new ObjectMapper();
            session.setAttribute("token",token);
            return objectMapper.writeValueAsString(hs);
        }else{
            return null;
        }


    }
}
